/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jaxb;

import hibernate.AlbumDAO;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import photogallery.Album;

/**
 *
 * @author ThuanPQ
 */
public class AlbumMarshaller {

    private Album[] albums;

    public AlbumMarshaller() {
    }

    public void createXML(String path) {
        Album[] albums;
        AlbumMarshaller am = new AlbumMarshaller();
        AlbumDAO ad = new AlbumDAO();
        albums = ad.getAllAlbums();
        for (Album entity : albums) {
            String coverUrl = ad.getAlbumCoverUrl(entity.getAlbumId());
            if (coverUrl.trim().equals("")) {
                entity.setCoverImagePath("images/album-cover-default.png");
            } else {
                entity.setCoverImagePath(coverUrl);
            }
        }

        if (albums != null && albums.length > 0) {
            Albums en = new Albums();
            for (Album entity : albums) {
                en.getAlbum().add(entity);
            }

            try {
                JAXBContext ctx = JAXBContext.newInstance(en.getClass());
                Marshaller mar = ctx.createMarshaller();
                mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                mar.marshal(en, new File(path + "/albums.xml"));
            } catch (JAXBException ex) {
                ex.printStackTrace();
            }
        }
    }

    public boolean checkXMLFile(String path) {
        File f = new File(path + "/albums.xml");

        if (f.exists()) {
            return true;
        }

        return false;
    }
}
